package com.sinacom.ibuilding.action;



import java.io.File;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.sinacom.ibuilding.beans.Member;
import com.sinacom.ibuilding.beans.Message;
import com.sinacom.ibuilding.beans.Role;
import com.sinacom.ibuilding.service.MemberService;
import com.sinacom.ibuilding.service.MessageService;
import com.sinacom.ibuilding.util.Constants;
import com.sinacom.ibuilding.util.Helper;
import com.sinacom.ibuilding.util.PageModel;

public class MailAction {
	
	private MemberService memberService = new MemberService();
	private MessageService messageService = new MessageService();
	private int page;
	private PageModel pageModel;
	private Message message;
	
	private File attach;
	private String attachFileName;
	private String attachContentType;
	
	private String filePath;
	private String messageId;
	
	private List memberList;
	
	private List roleTree;
	public String receivebox()throws Exception{
		HttpServletRequest request = ServletActionContext.getRequest(); 
		Member member = (Member) request.getSession().getAttribute("member");
		if(page < 1){
			page = 1;
		}
		pageModel = messageService.getMailReceiveBox(member, page);
		return "receivebox";
	}
	
	public String sendbox()throws Exception{
		HttpServletRequest request = ServletActionContext.getRequest(); 
		Member member = (Member) request.getSession().getAttribute("member");
		if(page < 1){
			page = 1;
		}
		pageModel = messageService.getMailSendBox(member, page);
		return "sendbox";
	}
	
	public String input()throws Exception{
	//	memberList = memberService.getMemberList(); 
		HttpServletRequest request = ServletActionContext.getRequest(); 
		Member member = (Member) request.getSession().getAttribute("member");
		Role r = member.getRole();
		setRoleTree(r);
		return "input";
	}
	
	public String edit()throws Exception{
	//	memberList = memberService.getMemberList(); 
		HttpServletRequest request = ServletActionContext.getRequest(); 
		Member member = (Member) request.getSession().getAttribute("member");
		Role r = member.getRole();
		setRoleTree(r);
		message = messageService.getMessageById(messageId);
		request.setAttribute("rmember", Helper.getRmember(message.getRmember()));
		return "input";
	}
	
	public void setRoleTree(Role r){
		if(r != null){
			List list = (List) Constants.cacheMap.get("roleTree");
			if(r.getVisituser()!=null && r.getVisituser().intValue()==1){
				roleTree = list;
			}else if(r.getVisituser() != null && r.getVisituser().intValue() == 2){
				if(list != null && list.size() > 0){
					for (int i = 0; i < list.size(); i++) {
						Role role = (Role) list.get(i);
						if("1".equals(role.getId())){
							if(roleTree == null) roleTree = new ArrayList();
							roleTree.add(role);
						}
					}
				}
			}
			
			
		} 
		if(roleTree !=null && roleTree.size() > 0){
			for (int i = 0; i < roleTree.size(); i++) {
				Role role = (Role) roleTree.get(i);
				if(role.getLogin() != null && role.getLogin().booleanValue()){
					List list = memberService.getMemberByRole(role.getId());
					if(list != null && list.size() > 0){
						role.setMemberList(list);
						role.setHasMember(Boolean.TRUE);
					}else{
						role.setHasMember(Boolean.FALSE);
					}
				}else{
					role.setMemberList(null);
					role.setHasMember(Boolean.FALSE);
				}
				if(role != null && role.getRoleList() != null && role.getRoleList().size() > 0){
					for (int j = 0; j < role.getRoleList().size(); j++) {
						Role role2 = (Role) role.getRoleList().get(j);
						if(role2.getLogin() != null && role2.getLogin().booleanValue()){
							List list = memberService.getMemberByRole(role2.getId());
							if(list != null && list.size() > 0){
								role2.setMemberList(list);
								role.setHasMember(Boolean.TRUE);
								role2.setHasMember(Boolean.TRUE);
							}else{
								role2.setHasMember(Boolean.FALSE);
							}
						}else{
							role2.setMemberList(null);
							role2.setHasMember(Boolean.FALSE);
						}
						if(role2 != null && role2.getRoleList() != null && role2.getRoleList().size() > 0){
							for (int k = 0; k < role2.getRoleList().size(); k++) {
								Role role3 = (Role) role2.getRoleList().get(k);
								if(role3.getLogin() != null && role3.getLogin().booleanValue()){
									List list = memberService.getMemberByRole(role3.getId());
									if(list != null && list.size() > 0){
										role3.setMemberList(list);
										role.setHasMember(Boolean.TRUE);
										role2.setHasMember(Boolean.TRUE);
										role3.setHasMember(Boolean.TRUE);
									}else{
										role3.setHasMember(Boolean.FALSE);
									}
								}else{
									role3.setMemberList(null);
									role3.setHasMember(Boolean.FALSE);
								}
							}
						}
					}
				}
			}
		}
	}
	
	public String reply()throws Exception{
		memberList = memberService.getMemberList();
		message = messageService.getMessageById(messageId);
		Member member = memberService.getMemberById(message.getSmember());
		if(message != null){ 
			message.setRmember(message.getSmember()+"#P#"+member.getUsername());
			HttpServletRequest request = ServletActionContext.getRequest(); 
			request.setAttribute("rmember", Helper.getRmember(message.getRmember()));
		}
		HttpServletRequest request = ServletActionContext.getRequest(); 
		Member sessonMember = (Member) request.getSession().getAttribute("member");
		Role r = sessonMember.getRole();
		setRoleTree(r);
		return "input";
	}
	
	public String replyAll()throws Exception{
		memberList = memberService.getMemberList();
        HttpServletRequest request = ServletActionContext.getRequest(); 
        Member member = (Member) request.getSession().getAttribute("member");
        message = messageService.getMessageById(messageId);
        String rmembers = message.getRmember();
        if(!StringUtils.isEmpty(rmembers)){
            /*String rms[] = rmembers.split(";");
            
            
            int j = 0;
            
            for (int i = 0; i < rms.length; i++) {
            	String rmdet = rms[i];
				String memberId = null;
				if(rmdet.startsWith("(") && rmdet.endsWith(")")){
					String[] rmdets = rmdet.replaceAll("\\(", "").replaceAll("\\)", "").split(",");
					memberId = rmdets[0];
				}else{
				}
                if(!memberId.equals(member.getId()) && !message.getSmember().equals(memberId)){
                    if(j != 0){
                        rems+=";";
                    }
                    rems = rems+rmdet;
                    j++;
                }
            }*/
            
            rmembers = removeContainMember(rmembers, member.getId(), member.getUsername());
        } 
        String retMember = message.getSmember();
        Member m = memberService.getMemberById(retMember); 
        String retMemberWrap = retMember+"#P#"+m.getUsername()+";";
        if(rmembers.indexOf(retMemberWrap) == -1){
        	rmembers=retMemberWrap+rmembers;
        } 
        
        request.setAttribute("rmember", Helper.getRmember(rmembers));
        
        message.setRmember(rmembers); 
        
		Role r = member.getRole();
		setRoleTree(r);
        return "input";
    }
	
	public String removeContainMember(String source,String id,String name){
		String oldStr = id+"#P#"+name+";";
		return source.replaceAll(oldStr, "");
	}
	
	public String forward()throws Exception{
	//	memberList = memberService.getMemberList(); 
		HttpServletRequest request = ServletActionContext.getRequest(); 
		Member member = (Member) request.getSession().getAttribute("member");
		Role r = member.getRole();
		if(r != null){
			List list = (List) Constants.cacheMap.get("roleTree");
			if(r.getVisituser()!=null && r.getVisituser().intValue()==1){
				roleTree = list;
			}else if(r.getVisituser()!=null && r.getVisituser().intValue()==2){
				if(list != null && list.size() > 0){
					for (int i = 0; i < list.size(); i++) {
						Role role = (Role) list.get(i);
						if("1".equals(role.getId())){
							if(roleTree == null) roleTree = new ArrayList();
							roleTree.add(role);
						}
					}
				}
			}
			
			
		} 
		if(roleTree !=null && roleTree.size() > 0){ 
			for (int i = 0; i < roleTree.size(); i++) {
				Role role = (Role) roleTree.get(i);
				role.setMemberList(memberService.getMemberByRole(role.getId()));
				if(role != null && role.getRoleList() != null && role.getRoleList().size() > 0){
					for (int j = 0; j < role.getRoleList().size(); j++) {
						Role role2 = (Role) role.getRoleList().get(j);
						role2.setMemberList(memberService.getMemberByRole(role2.getId()));
						if(role2 != null && role2.getRoleList() != null && role2.getRoleList().size() > 0){
							for (int k = 0; k < role2.getRoleList().size(); k++) {
								Role role3 = (Role) role2.getRoleList().get(k);
								role3.setMemberList(memberService.getMemberByRole(role3.getId()));
							}
						}
					}
				}
			}
		}
		message = messageService.getMessageById(messageId);
		message.setRmember(null);
		return "input";
	}
	
	public String readmail()throws Exception{
		messageService.readMessage(messageId);
		message = messageService.getMessageById(messageId);
		if(message != null){
			String rmembers=  message.getRmember();
			if(!StringUtils.isEmpty(rmembers)){
	            HttpServletRequest request = ServletActionContext.getRequest(); 
	            request.setAttribute("rmember", Helper.getRmember(rmembers));
			}
		}
		return "readmail";
	}
	
	public String send()throws Exception{
		HttpServletRequest request = ServletActionContext.getRequest(); 
		Member member = (Member) request.getSession().getAttribute("member");
		messageService.sendMail(member, message); 
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        pw = response.getWriter();
        Map map = new HashMap();  
        map.put("success", "true");
        map.put("msg", "发送成功");
        pw.print(JSONObject.fromObject(map));
		return null;
	}
	
	public String resend()throws Exception{
		HttpServletRequest request = ServletActionContext.getRequest(); 
		Member member = (Member) request.getSession().getAttribute("member");
		Message m = messageService.getMessageById(messageId);
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        pw = response.getWriter();
        Map map = new HashMap();  
		if(m != null){
			if(messageService.sendMail(member, m,true)){
				map.put("success", "true");
		        map.put("msg", "发送成功"); 
		        pw.print(JSONObject.fromObject(map));
		        return null;
			}
		}
		
		map.put("success", "false");
        map.put("msg", "发送失败"); 
        pw.print(JSONObject.fromObject(map));
       
        
        
		return null;
	}
	
	public String uploadAttach()throws Exception{
		ServletContext context = ServletActionContext.getServletContext();
		String targetDirectory = context.getRealPath("/attach");   
		DateFormat format = new SimpleDateFormat("yyyyMMdd");   
        String formatDate = format.format(new Date());
        long time = (new Date()).getTime();
        File target = new File(targetDirectory+"/"+formatDate+"/"+time, attachFileName);   
           
        FileUtils.copyFile(attach, target); 
        
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        pw = response.getWriter();
        Map map = new HashMap();
        map.put("fileName", attachFileName);
        map.put("filePath", "attach/"+formatDate+"/"+time+"/"+attachFileName);
        pw.print(JSONObject.fromObject(map));
		return null;
	}
	
	public String cancelAttach()throws Exception{
		if(!StringUtils.isEmpty(filePath)){ 
			ServletContext context = ServletActionContext.getServletContext();
			String realPath = context.getRealPath("/");
			File f = new File(realPath+filePath);
			if(f.exists()){
				f.delete();
			}
		}
		HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        pw = response.getWriter();
        Map map = new HashMap();
        map.put("success", "true");
        pw.print(JSONObject.fromObject(map));
		return null;
	}
	
	public String delete()throws Exception{
	    HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        pw = response.getWriter();
        Map map = new HashMap();
        HttpServletRequest request = ServletActionContext.getRequest(); 
        Member member = (Member) request.getSession().getAttribute("member");
        if(member != null){
            try{
                Message message = messageService.getMessageById(messageId);
                if(message.getMember().equals(member.getId())){
                    messageService.deleteMessage(messageId);   
                    map.put("success", "true");
                }else{
                    map.put("success", "false");
                    map.put("msg", "您没有删除该邮件的权利！");
                }
                
            }catch(Exception e){
                e.printStackTrace();
                map.put("success", "false");
                map.put("msg", "删除邮件失败!");
            }
        }else{
            map.put("success", "false");
            map.put("msg", "您还没有登录!");
        }
        
        pw.print(JSONObject.fromObject(map));
	    return null;
	}
	
	public MemberService getMemberService() {
		return memberService;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	public PageModel getPageModel() {
		return pageModel;
	}

	public void setPageModel(PageModel pageModel) {
		this.pageModel = pageModel;
	}
	
	public Message getMessage() {
		return message;
	}

	public void setMessage(Message message) {
		this.message = message;
	}
	
	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}
	
	
	
	

	public File getAttach() {
		return attach;
	}

	public void setAttach(File attach) {
		this.attach = attach;
	}

	public String getAttachFileName() {
		return attachFileName;
	}

	public void setAttachFileName(String attachFileName) {
		this.attachFileName = attachFileName;
	}

	public String getAttachContentType() {
		return attachContentType;
	}

	public void setAttachContentType(String attachContentType) {
		this.attachContentType = attachContentType;
	}

	public MessageService getMessageService() {
		return messageService;
	}

	public void setMessageService(MessageService messageService) {
		this.messageService = messageService;
	}
	
	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}
	

	public String getMessageId() {
		return messageId;
	}

	public void setMessageId(String messageId) {
		this.messageId = messageId;
	}
	

	public List getMemberList() {
		return memberList;
	}

	public void setMemberList(List memberList) {
		this.memberList = memberList;
	}
	
	public List getRoleTree() {
		return roleTree;
	}

	public void setRoleTree(List roleTree) {
		this.roleTree = roleTree;
	}

	public static void main(String[] args) {
		MailAction mailAction = new MailAction();
		System.out.println(mailAction.removeContainMember("yulong#P#于龙;feixiang#P#飞翔;yulong2#P#于龙;admin#P#admin;", "admin", "admin"));
	}
	
	
}
